package com.llxz.blog.msm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.llxz.blog.msm.service.MsmService;
import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Map;
import java.util.Properties;

/**
 * Created by IntelliJ IDEA.
 *
 * @author zzh
 * @description:. date: 2021/9/4 10:18
 */

@Service
public class MsmServiceImpl implements MsmService {
    @Override
    public boolean send(Map<String, Object> param, String phone) {
        if(StringUtils.isEmpty(phone)) return false;

        System.out.println("msm service");

        DefaultProfile profile =
                DefaultProfile.getProfile("default", "LTAI4GFJxSQkDpmm6jbBajKs", "LmdS24qTzPgSA3AgtQlNFEQxli3L2u");
        IAcsClient client = new DefaultAcsClient(profile);

        //设置相关固定的参数
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");


        //设置发送相关的参数
        request.putQueryParameter("PhoneNumbers",phone); //手机号
        //request.putQueryParameter("SignName","浪里行舟博客"); //申请阿里云 签名名称
        //request.putQueryParameter("TemplateCode","SMS_200175526"); //申请阿里云 模板code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param)); //验证码数据，转换json数据传递
        System.out.println(JSONObject.toJSONString(param) + " =============");

        try {
            //最终发送
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            return success;
        }catch(Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    @Override
    public boolean sendByEmail(Map<String, Object> param, String email) {
        try {
            Properties prop = new Properties();
            // 开启debug调试，以便在控制台查看
            prop.setProperty("mail.debug", "true");
            // 设置邮件服务器主机名
            prop.setProperty("mail.host", "smtp.qq.com");
            // 发送服务器需要身份验证
            prop.setProperty("mail.smtp.auth", "true");
            // 发送邮件协议名称
            prop.setProperty("mail.transport.protocol", "smtp");
            // 开启SSL加密，否则会失败
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", sf);
            // 创建session
            Session session = Session.getInstance(prop);
            // 通过session得到transport对象
            Transport ts = session.getTransport();
            // 连接邮件服务器：邮箱类型，帐号，POP3/SMTP协议授权码 163使用：smtp.163.com
            ts.connect("smtp.qq.com", "3293536763@qq.com", "gsynuevybakmdbja");
            // 创建邮件
            Message message = createSimpleMail(session,param,email);
            // 发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            ts.close();

        } catch (Exception e) {
            throw new RuntimeException("验证码发送异常");

        }

        return true;
    }

    private Message createSimpleMail(Session session, Map<String, Object> param,String email) {
        MimeMessage message = new MimeMessage(session);
        // 创建邮件对象
        try {

            // 指明邮件的发件人
            message.setFrom(new InternetAddress("3293536763@qq.com"));
            // 指明邮件的收件人，发件人和收件人如果是一样的，那就是自己给自己发
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
            // 邮件的标题
            message.setSubject("JavaMail测试");
            // 邮件的文本内容
            message.setContent("欢迎您注册【浪里行舟博客】,账号注册验证码为(一分钟有效):"+param.get("code")+",请勿回复此邮箱", "text/html;charset=UTF-8");
        } catch (Exception e) {

        }

        // 返回创建好的邮件对象
        return message;

    }
}
